//
//  CLseekViewController.m
//  I-want-go
//
//  Created by dllo on 15/10/31.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "CLseekViewController.h"
#import "CLtool.h"
#import "CLseekCollectionCell.h"
#import "CLseek.h"
#import "CLinterViewController.h"
#import "CLstrollViewController.h"
#import "CLscreen.h"
@interface CLseekViewController ()<UICollectionViewDataSource, UICollectionViewDelegate>
@property(nonatomic, retain)UICollectionView *myCollectionView;
@property(nonatomic, retain)NSMutableArray *arr;
@property(nonatomic, assign)NSInteger page;
@end

@implementation CLseekViewController

- (void)dealloc {
    [_arr release];
    [_str release];
    [_myCollectionView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(150 * SWIDTH, 200 * SHEIGHT);
    flowLayout.sectionInset = UIEdgeInsetsMake(10 * SWIDTH, 15 * SHEIGHT, 5 * SWIDTH, 10 * SHEIGHT);
    self.myCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, 375 * SWIDTH, 603 * SHEIGHT) collectionViewLayout:flowLayout];
    [self.view addSubview:self.myCollectionView];
    [_myCollectionView release];
    [self.myCollectionView registerClass:[CLseekCollectionCell class] forCellWithReuseIdentifier:@"reuse"];
    self.myCollectionView.dataSource = self;
    self.myCollectionView.delegate = self;
    
    self.myCollectionView.footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerAction)];

    [self createData];
    
    
}

- (void)footerAction {
    
    self.page = 0;
    self.page++;
    NSString *stre = @"http://api.xiangqu.com/search/list";
    NSURL *urli = [NSURL URLWithString:stre];
    NSMutableURLRequest *serequest = [NSMutableURLRequest requestWithURL:urli];
    [serequest setHTTPMethod:@"POST"];
    NSString *body = [NSString stringWithFormat: @"fromType=-1&imageHD=2&key=c180a988bc3d83cdf9a98953113fdd86&keyword=%@&page=%ld&t=1446295265858&userid=705811&version=3.5.4", self.str, self.page];
    NSData *bodyD = [body dataUsingEncoding:NSUTF8StringEncoding];
    [serequest setHTTPBody:bodyD];
    [NSURLConnection sendAsynchronousRequest:serequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        
        NSMutableArray *arArr = [NSMutableArray array];
        arArr = [CLseek baseModelByArr:dic[@"data"][@"records"]];
        for (CLseek *seek in arArr) {
            [self.arr addObject:seek];
        }
        [self.arr removeLastObject];
        [self.myCollectionView.footer endRefreshing];
        [self.myCollectionView reloadData];
        
    }];
}


- (void)createData {
    
    NSString *stre = @"http://api.xiangqu.com/search/list";
    NSURL *urli = [NSURL URLWithString:stre];
    NSMutableURLRequest *serequest = [NSMutableURLRequest requestWithURL:urli];
    [serequest setHTTPMethod:@"POST"];
    NSString *body = [NSString stringWithFormat: @"fromType=-1&imageHD=2&key=c180a988bc3d83cdf9a98953113fdd86&keyword=%@&page=0&t=1446295265858&userid=705811&version=3.5.4", self.str];
    NSData *bodyD = [body dataUsingEncoding:NSUTF8StringEncoding];
    [serequest setHTTPBody:bodyD];
    [NSURLConnection sendAsynchronousRequest:serequest queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
//         NSLog(@"%@", self.str);
        NSLog(@"%@", dic[@"data"][@"records"]);
        
        self.arr = [NSMutableArray array];
        self.arr = [CLseek baseModelByArr:dic[@"data"][@"records"]];
        if (self.arr.count == 0) {
            UIAlertController *aleryController = [UIAlertController alertControllerWithTitle:@"对不起" message:@"搜索的商品不存在" preferredStyle:UIAlertControllerStyleAlert];
            [self presentViewController:aleryController animated:YES completion:nil];
            UIAlertAction *leftAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
                // 模态跳转
                CLstrollViewController *strVC = [[CLstrollViewController alloc] init];
                //            [self presentViewController:strVC animated:YES completion:nil];
                [self.navigationController pushViewController:strVC animated:YES];
            }];
            
            UIAlertAction *rightAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
            [aleryController addAction:leftAction];
            [aleryController addAction:rightAction];

        }
       
        [self.myCollectionView reloadData];
        
    }];
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    NSLog(@"%ld", self.arr.count);
            return self.arr.count;
    
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CLseekCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"reuse" forIndexPath:indexPath];
    CLseek *seek = self.arr[indexPath.row];
    
    
    
    [cell.productImage sd_setImageWithURL:[NSURL URLWithString:seek.image]];
    cell.titleLabel.text = seek.brand;
    cell.titleLabel.textColor = [UIColor whiteColor];
    cell.contetLabel.text = seek.productDescription;
    
   //////// 关键字高亮
    NSMutableAttributedString *cnnameString = [[NSMutableAttributedString alloc] initWithString:cell.contetLabel.text];
    NSLog(@"%@", self.searchText);
    NSRange range = [cell.contetLabel.text rangeOfString:self.searchText];
    [cnnameString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:range];
    cell.contetLabel.attributedText = cnnameString;
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CLseek *seek = self.arr[indexPath.row];
    CLinterViewController *intVC = [[CLinterViewController alloc] init];
    [self.navigationController pushViewController:intVC animated:YES];
    intVC.interId = seek.productId;
    
}

- (void)viewWillAppear:(BOOL)animated {
    
    self.tabBarController.tabBar.hidden = YES;
    
}

- (void)viewWillDisappear:(BOOL)animated {
    self.tabBarController.tabBar.hidden = NO;
}








- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
